package mj.scott.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import mj.scott.pojo.entity.Category;
import mj.scott.mapper.CategoryMapper;
import mj.scott.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 菜品分类 服务实现类
 * @author Scott
 * @since 2025-08-15
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public Category saveCategory(Category category) {
        // 校验分类名称是否已存在
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", category.getName());
        Category existing = baseMapper.selectOne(queryWrapper);
        if (Objects.nonNull(existing)) {
            throw new RuntimeException("分类名称已存在");
        }
        // 保存分类信息
        baseMapper.insert(category);
        return category;
    }

    @Override
    public Category updateCategory(Category category) {
        // 校验分类是否存在
        Category existing = baseMapper.selectById(category.getId());
        if (Objects.isNull(existing)) {
            throw new RuntimeException("分类不存在");
        }
        // 校验名称是否重复（排除当前记录）
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", category.getName())
                .ne("id", category.getId());
        if (baseMapper.selectCount(queryWrapper) > 0) {
            throw new RuntimeException("分类名称已存在");
        }
        // 更新分类信息
        baseMapper.updateById(category);
        return baseMapper.selectById(category.getId());
    }

    @Override
    public void deleteCategory(Long id) {
        // 校验分类是否存在
        Category category = baseMapper.selectById(id);
        if (Objects.isNull(category)) {
            throw new RuntimeException("分类不存在");
        }
        // 这里可以添加判断：如果分类下有菜品，不允许删除
        //if (dishService.countByCategoryId(id) > 0)
        // { throw new RuntimeException("分类下有菜品，无法删除"); }
        // 删除分类
        baseMapper.deleteById(id);
    }

    @Override
    public List<Category> getAllCategories() {
        // 查询所有分类并按ID排序
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("id");
        return baseMapper.selectList(queryWrapper);
    }

    //用户分类查询
    @Override
    public List<Category> getAllCategory() {
        return categoryMapper.selectAll();
    }
}
